package com.wjw.cloud.service.impl;

import com.github.pagehelper.PageHelper;
import com.wjw.cloud.dto.GoodsParam;
import com.wjw.cloud.mapper.GoodsMapper;
import com.wjw.cloud.model.Goods;
import com.wjw.cloud.service.GoodsService;
import com.wjw.cloud.util.ElasticSearchUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class GoodsServiceImpl implements GoodsService {

    @Autowired
    private GoodsMapper goodsMapper;

    @Autowired
    private ElasticSearchUtil elasticSearchUtil;

    @Override
    public int insert(GoodsParam goodsParam) {
        Goods goods = new Goods();
        BeanUtils.copyProperties(goodsParam, goods);
        return goodsMapper.insertSelective(goods);
    }

    @Override
    public int delete(Integer id) {
        return goodsMapper.deleteByPrimaryKey(id);
    }

    @Override
    public int update(Goods goods) {
        return goodsMapper.updateByPrimaryKeySelective(goods);
    }

    @Override
    public List<Goods> list(String describe, String storeName, Integer post, Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        return goodsMapper.selectListByPage(describe, storeName, post);
    }

    @Override
    public List<Goods> frontList(Map<String, Object> map) {

        if (map.get("pageNum") == null || "".equals(map.get("pageSize")))
        {
            map.put("pageNum", 1);
        }
        if (map.get("pageSize") == null || "".equals(map.get("pageSize")))
        {
            map.put("pageSize", 10);
        }
        PageHelper.startPage(Integer.parseInt(map.get("pageNum").toString()), Integer.parseInt(map.get("pageSize").toString()));

        if ( (map.get("lowest") == null || "".equals(map.get("lowest"))) && (map.get("tallest") != null && !"".equals(map.get("tallest"))) )
        {
            map.put("lowest", "0");
        }
        else if ( (map.get("lowest") != null && !"".equals(map.get("lowest"))) && (map.get("tallest") == null || "".equals(map.get("tallest"))) )
        {
            map.put("tallest", "999999");
        }

        return goodsMapper.selectFrontList(map);

    }

    @Override
    public HashMap<String, Object> frontListByES(Map<String, Object> map) {

        String value = (String) map.get("describe");
        int pageNum = Integer.parseInt((String) map.get("pageNum"));
        int pageSize = Integer.parseInt((String) map.get("pageSize"));

        HashMap<String, Object> hashMap = elasticSearchUtil.searchDocument("describe", value, pageNum, pageSize);

        return hashMap;

    }

}
